<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Order;

class Shopcart extends \Service\Common\BaseModel
{
    protected $name = 'shopcart';

    //加入
    public function addCart($data, $uid)
    {
        $goods_id = $data['goods_id'];
        $goods = M('goods')->find($goods_id);
        if (!$goods) {
            throw new \Exception("无效的商品");
        }

        $cart = $this->where([
            'uid' => $uid,
            'goods_id' => $goods_id,
        ])->find();
        if ($cart) {
           /* $spec_list = [
                [
                    'id' => 3,
                    'name' => '颜色',
                    'v' => '黑色',
                ],
                [
                    'id' => 4,
                    'name' => '尺码',
                    'v' => 'S',
                ],
            ];*/
            $this->save([
                'id' => $cart['id'],
                'buy_num' => ['exp', 'buy_num+1'],
                'spec_list' => $data['spec_value'],
            ]);
            return;
        }

        $this->add([
            'uid' => $uid,
            'goods_id' => $goods_id,
            'buy_num' => 1,
            'create_time' => date('Y-m-d H:i:S'),
            'spec_list' => $data['spec_value'],
        ]);
    }

    //修改购买数量
    public function changeNum($data, $uid)
    {
        $goods_id = $data['goods_id'];
        $buy_num = $data['buy_num'];
        $cart = $this->where(['uid' => $uid, 'goods_id' => $goods_id])->find();
        if ($cart) {
            $this->save([
                'id' => $cart['id'],
                'buy_num' => $buy_num,
//                'spec_list' => json_encode($spec_list),
            ]);
        }
    }

    //移除
    public function remove($goods_ids, $uid)
    {
        $ids = is_array($goods_ids) ? $goods_ids : [];
        foreach ($ids as $id) {
            if (is_numeric($id)) {
                $this->where([
                    'uid' => $uid,
                    'goods_id' => $id
                ])->delete();
            }
        }
    }

    //下单成功清空购物车
    public function emptyCart($uid)
    {
        $this->where(['uid' => $uid])->delete();
    }

    //我的购物车


    public function lists($uid)
    {
        $list = $this->where(['uid' => $uid])->select();
        $result = [];
        foreach ($list as $row) {
            $goods = OE('goods')->getDetail($row['goods_id'], $uid);
            $goods['buy_num'] = $row['buy_num'];
            $goods['goods_id'] = $row['goods_id'];
            $goods['spec_label'] = $row['spec_list'];

            $result[] = $goods;
        }
        return $result;
    }
}